import userService from "@/api/services/system/userService";
import { Button, Form, Input, Modal, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import { useEffect, useState } from "react";
import type { UserInfo } from "#/entity";

interface UserSelectorProps {
	open: boolean;
	onCancel: () => void;
	onOk: (selectedUsers: UserInfo[]) => void;
	excludeUserIds?: string[]; // 已分配的用户ID，用于过滤
}

export default function UserSelector({ open, onCancel, onOk, excludeUserIds = [] }: UserSelectorProps) {
	const [loading, setLoading] = useState(false);
	const [users, setUsers] = useState<UserInfo[]>([]);
	const [selectedUsers, setSelectedUsers] = useState<UserInfo[]>([]);
	const [queryParams, setQueryParams] = useState({
		account: "",
		name: "",
		page: 1,
		pageSize: 10,
	});
	const [total, setTotal] = useState(0);

	const columns: ColumnsType<UserInfo> = [
		{ title: "用户名", dataIndex: "account" },
		{ title: "姓名", dataIndex: "name" },
		{ title: "手机号", dataIndex: "phone" },
	];

	const fetchUsers = async () => {
		try {
			setLoading(true);
			const res = await userService.pageList(queryParams);
			// 过滤掉已分配的用户
			const filteredUsers = res.records.filter((user) => !excludeUserIds.includes(user.id));
			setUsers(filteredUsers);
			setTotal(res.total);
		} catch (error) {
			console.error("获取用户列表失败:", error);
		} finally {
			setLoading(false);
		}
	};

  useEffect(() => {
		fetchUsers();
	}, [queryParams]);

	const handleSearch = (values: any) => {
		setQueryParams((prev) => ({
			...prev,
			...values,
			page: 1,
		}));
	};

	const handlePageChange = (page: number, pageSize: number) => {
		setQueryParams((prev) => ({
			...prev,
			page,
			pageSize,
		}));
	};

	const handleOk = () => {
		onOk(selectedUsers);
	};

	return (
		<Modal title="选择用户" open={open} onCancel={onCancel} onOk={handleOk} width={800} destroyOnClose>
			<Form layout="inline" onFinish={handleSearch} className="mb-4">
				<Form.Item name="account" label="用户名">
					<Input placeholder="请输入用户名" allowClear />
				</Form.Item>
				<Form.Item name="name" label="姓名">
					<Input placeholder="请输入姓名" allowClear />
				</Form.Item>
				<Form.Item>
					<Button type="primary" htmlType="submit">
						查询
					</Button>
				</Form.Item>
			</Form>
      <div className="h-4" />
			<Table
				rowKey="id"
				loading={loading}
				columns={columns}
				dataSource={users}
				rowSelection={{
					type: "checkbox",
					onChange: (_, selectedRows) => {
						setSelectedUsers(selectedRows);
					},
				}}
				pagination={{
					total,
					current: queryParams.page,
					pageSize: queryParams.pageSize,
					onChange: handlePageChange,
				}}
			/>
		</Modal>
	);
}
